package com.gitee.sop.notifyexample.controller;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.gitee.sop.sdk.sign.SignUtil;
import com.gitee.sop.sdk.sign.SopSignException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 处理回调
 *
 * @author 六如
 */
@RestController
@Slf4j
public class DemoCallbackController {
    // 平台下发的公钥
    String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAj0CaMfudpfsrzgT7014aIGQPiEHvk5JPMlHH7YI5JYk+yAgePntojJ8/q1nmeHAauJqEYuCZHfqcjxzLM2hVvttrXtiacTMlr/ea9CGJtx4m20ltrsPOIXPXXZUToxXgO7X1FNvgXgeBBPcWLrsmJUgAQbM1KG/bo9QdNp/cFf5tBuo+1fXB9qXlZnSCbvQwrhfDGAF7NmEYkvkoQeys9YkASAl+zeEOXdBkPQjKDd9USyb/tIkrgLmeo0EOp+PytmEOAsMPSeIEdRcwrgg16X9BvMvnPKLTetQxXILG7r6kkkLj1pVA8EGinRDFu0jwp/Wu+wwUvRlpDRvUbyWEOQIDAQAB";

    /**
     * 模拟客户端处理接口回调
     * 回调接口：http://127.0.0.1:7074/notify/callback
     * 返回状态200表示成功收到请求
     * 返回非200表示处理失败，平台会进行重试，重试机制见：com.gitee.sop.notify.service.NotifyBizService#timeLevel
     * @param content
     * @return
     */
    @PostMapping("notify/callback")
    public ResponseEntity<String> callback(@RequestBody String content) {
        log.info("收到回调通知, content={}", content);
        JSONObject jsonObject = JSON.parseObject(content);
        // 签名校验
        if (!checkSign(jsonObject)) {
            return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
                    .body("ERR");
        }
        log.info("签名验证通过，处理业务逻辑");
        String method = jsonObject.getString("method");
        // 判断业务类型，处理不同业务
        switch (method) {
            // 处理订单创建回调
            case "shop.order.create": {
                JSONObject bizContent = jsonObject.getJSONObject("biz_content");
                log.info("业务参数，bizContent={}", bizContent);
                break;
            }
            case "shop.order.close": {
                // 处理订单关闭回调
                break;
            }
            default:{}
        }
        // 返回200状态即可
        return ResponseEntity.ok("success");
    }

    private boolean checkSign(JSONObject jsonObject) {
        try {
            return SignUtil.rsaCheckV2(jsonObject, publicKey, "UTF-8", "RSA2");
        } catch (SopSignException e) {
            log.error("签名校验错误, jsonObject={}", jsonObject, e);
            return false;
        }
    }
}
